<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/11
 * Time: 10:36
 */

namespace app\api\controller;


use app\admin\model\room\Room;
use app\common\controller\Api;
use function EasyWeChat\Payment\get_client_ip;
use think\Request;
use Yansongda\Pay\Pay;

class Payment extends Api
{
    protected $noNeedLogin = ['wx_notify'];
    public function pay()
    {
        $order_id = $this->request->param('order_id'); //订单id
        $type = $this->request->param('type');         //支付类型.
        $identifying = $this->request->param('identifying');
        $order_type = $this->request->param('order_type');//订单类型
        $openid = $this->request->param('openid', '0');
        if ($order_type == 'consult_order') {
            $order = new \app\admin\model\order\Order();
            $orderInfo = $order->get($order_id);
            if ($orderInfo->pay_status == 0 || $orderInfo->status == 1) {
                $this->error('当前订单已支付');
            }
            $orderArr = [
                'order_sn' => $orderInfo->order_sn,
                'price' => $orderInfo->price,
                'openid' => $openid,
                'consult_type' => $orderInfo->consult_type,
            ];
           return $this->pays($identifying, $orderArr);
        }

    }

    public function pays($identifying, $order)
    {
        switch ($identifying) {
            case "ali_web":  //支付宝电脑支付
                $pay = new Pay(['alipay' => $this->AliConfig()]);
                $order_biz = [
                    'out_trade_no' => $order['order_sn'],
                    'total_amount' => $order['price'],
                    'subject' => $order['consult_type']
                ];
                return $pay->driver('alipay')->gateway('web')->pay($order_biz);
                break;
            case "ali_wap":  //支付宝手机网站支付
                $pay = new Pay(['alipay' => $this->AliConfig()]);
                $order_biz = [
                    'out_trade_no' => $order['order_sn'],
                    'total_amount' => $order['price'],
                    'subject' => $order['consult_type']
                ];
                return $pay->driver('alipay')->gateway('wap')->pay($order_biz);
                break;

            case "ali_app":  //支付宝app支付
                $this->error('当前支付未开通');
                break;
            case "wx_mp":      //微信公众号支付
                $this->error('当前支付未开通');
                break;
            case "wx_miniapp":    //微信小程序支付
                if (empty($order['openid'])) {
                    $this->error('缺少openid');
                }
                $pay = new Pay(['wechat' => $this->wxConfig()]);
                $order_biz = [
                    'out_trade_no' => $order['sn'],
                    'total_fee' => $order['price'] * 100,
                    'openid' => $order['openid'],
                    'spbill_create_ip' => get_client_ip(),
                    'body' => $order['consult_type']
                ];
                return $pay->driver('wechat')->gateway('miniapp')->pay($order_biz);
                break;
            case "wx_wap":         //h5支付
                break;
            case "wx_scan":          //微信扫码支付
                break;
            default:
                $this->error('请选择支付方式');
                break;
        }
    }

    /**
     * 微信配置
     * */
    protected function wxConfig()
    {
        return [
            'appid' => config('aliPay.appid'), // APP APPID
            'app_id' => config('aliPay.app_id'), // 公众号 APPID
            'miniapp_id' => config('aliPay.miniapp_id'), // 小程序 APPID
            'mch_id' => config('aliPay.mch_id'),
            'key' => config('aliPay.key'),
            'cert_client' => config('aliPay.cert_client'), // optional，退款等情况时用到
            'cert_key' => config('aliPay.cert_key'),// optional，退款等情况时用到
            'notify_url' => input('server.REQUEST_SCHEME') . '://' . input('server.SERVER_NAME') . 'api/payment/wx_notify',
        ];
    }

    /**
     * 支付宝配置
     * */
    protected function AliConfig()
    {
        return [
            'app_id' => config('aliPay.app_id'),
            'ali_public_key' => config('aliPay.ali_public_key'),
            // 加密方式： **RSA2**
            'private_key' => config('aliPay.private_key'),
            'notify_url' => input('server.REQUEST_SCHEME') . '://' . input('server.SERVER_NAME') . 'api/payment/ali_notify',
            'return_url' => input('server.REQUEST_SCHEME') . '://' . input('server.SERVER_NAME') . 'api/payment/ali_return',
        ];
    }

    /**
     * 微信支付回调
     * */

    public function wx_notify(Request $request)
    {
        $pay = new Pay(['wechat' => $this->wxConfig()]);
        $verify = $pay->driver('wechat')->gateway('miniapp')->verify($request->getContent());
        if ($verify) {
            file_put_contents('notify.txt', "收到来自微信的支付异步通知\r\n" . json_encode($verify), FILE_APPEND);
            $out_trade_no = $verify['out_trade_no'];
            $transaction_id = $verify['transaction_id'];
            $order = new \app\admin\model\order\Order();
            $orderInfo = $order->where('order_sn', $out_trade_no)->find();
            if ($orderInfo['pay_status'] == 1) {

            } else {
                $updata = [
                    'pay_status' => '1',
                    'pay_time' => date('Y-m-d H:i:s'),
                    'pay_type' => 'wxpay',
                    'transaction' => $transaction_id,
                ];
                $order->where('order_sn', $out_trade_no)->update($updata);
                //创建通话房间号
                $room = new Room();
                $room->createRoom($orderInfo['order_id']);
            }
            $pay->success();
        }
        $pay->success();
    }
}